package edu.bit.water.controller;

import java.text.ParseException;
import java.util.*;

import com.alibaba.excel.EasyExcel;
import com.alibaba.fastjson.JSONArray;
import edu.bit.water.dto.DateUtils;
import edu.bit.water.dto.WarningRule;
import edu.bit.water.dto.WaterCondition;
import edu.bit.water.entity.EntityWater;
import edu.bit.water.entity.UserEntity;
import edu.bit.water.util.DateTimeUtil;
import edu.bit.water.util.ExcelUtil;

import edu.bit.water.util.ListToSqlString;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;


import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;


import edu.bit.water.service.EntityWaterService;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

@Controller
@RequestMapping("/entity_water")
public class EntityWaterController extends BaseController{

    @Autowired
    private EntityWaterService entityWaterService;

//	/**
//	 * @return 返回实体表中有哪些字段
//	 */
//	@RequestMapping("/selectColumn")
//	@ResponseBody
//	public String selectColumn() {
//		List<Map<String, String>> fields = new ArrayList<>();
//		Map<String, String> field = new HashMap<>();
//
//		field.put("field", "ID");
//		field.put("title", "标示符");
//		fields.add(field);
//
//		field = new HashMap<>();
//
//		field.put("field", "SENSOR_NAME");
//		field.put("title", "设备名称");
//		fields.add(field);
//
//		field = new HashMap<>();
//
//		field.put("field", "CREATED_AT");
//		field.put("title", "时间");
//		fields.add(field);
//
//		for (Column column : metaWaterService.selectColumn()) {
//			field = new HashMap<>();
//			// oracle 里查出来都是大写的尴尬了，与下面select相对应
//			field.put("field", column.enName.toUpperCase());
//			field.put("title", column.csName);
//			fields.add(field);
//		}
//		return JSON.toJSONString(fields);
//	}

//	/**
//	 * @param list 前端传递过来的数据
//	 * @return 返回实体表中有哪些字段
//	 *
//	 */
//	@RequestMapping("/insert_notime")
//	@ResponseBody
//	public Map<String, Object> insertnotime(@RequestBody List<Object> list) {
//		List<String> lineColumn = ColumnUtil.columnToEnName(metaWaterService.selectColumn()); // 查询实体表中已有字段
//		Date aDate = new Date();
//		list.add(1, new java.sql.Date(aDate.getTime()));
//		return entityWaterService.insertEntityWater(list, lineColumn);
//	}

    @RequestMapping("/delete")
    @ResponseBody
    public Map<String, Object> delete(@RequestBody List<Integer> ids) {
        StringBuilder temp = new StringBuilder(ids.toString());
        temp.setCharAt(0, '(');
        temp.setCharAt(temp.length() - 1, ')');
        entityWaterService.deleteEntityWater(new String(temp));
        Map<String, Object> modelMap = new HashMap<>();
        modelMap.put("status", "success");
        return modelMap;
    }

    @RequestMapping(value = "/selectall", method = RequestMethod.GET)
    @ResponseBody
    private Map<String, Object> select() {
        Map<String, Object> modelMap = new HashMap<>();
        List<Map<String, Object>> entityWaterlist = entityWaterService.selectEntityWater();
        modelMap.put("rows", entityWaterlist);
        return modelMap;
    }

    @RequestMapping(value = "/selectall_by_companyid", method = RequestMethod.GET)
    @ResponseBody
    private Map<String, Object> selectAllByCompanyId(String company_id) throws ParseException {
        Map<String, Object> modelMap = new HashMap<>();
        List<Map<String, Object>> entityWaterlist = entityWaterService.selectEntityWaterByCompanyId(company_id);
        modelMap.put("rows", entityWaterlist);
        return modelMap;
    }

    @RequestMapping(value = "/selectall_by_companyid_and_search", method = RequestMethod.GET)
    @ResponseBody
    private Map<String, Object> selectAllByCompanyIdAndSearch(@RequestParam("limit") int limit, @RequestParam("page") int page, @RequestParam("company_id") String company_id,
                                                     @RequestParam("searchContent") String searchContent) throws ParseException {
        if(searchContent.equals("-")) {
            searchContent = "";
        }
        int begin = (page - 1) * limit;
        int end = begin + limit;
        Map<String, Object> modelMap = new HashMap<>();
        List<Map<String, Object>> entityWaterlist = entityWaterService.selectEntityWaterByCompanyIdAndSearch(company_id, begin, end, searchContent);
        modelMap.put("rows", entityWaterlist);
        int sumsize = entityWaterService.selectEntityWaterSumByCompanyId(company_id, searchContent);
        modelMap.put("total", sumsize);
        return modelMap;
    }

    /**
     * 根绝企业id查询该企业各个设备最新的采集数值
     * @param techProcessId
     * @return
     */
//    @RequestMapping(value = "/selectNewBytechProcessId", method = RequestMethod.GET)
//    @ResponseBody
//    private Map<String, Object> selectNewByCompanyId(@RequestParam("techProcessId") String techProcessId) {
//        System.out.println("fxz------------" + techProcessId);
//        Map<String, Object> modelMap = new HashMap<>();
//        List<EntityWater> entityWaterlist = entityWaterService.selectNewByBusinessId(techProcessId);
//        modelMap.put("rows", entityWaterlist);
//        return modelMap;
//    }
    @RequestMapping(value = "/selectNewByTechProcessId", method = RequestMethod.GET)
    @ResponseBody
    public Map<String, Object> selectNewByTechProcessId(@RequestParam("techProcessId") String techProcessId) throws ParseException {
        Map<String, Object> modelMap = new HashMap<>();
        List<EntityWater> entityWaterlist = entityWaterService.selectNewByBusinessId(techProcessId);
        modelMap.put("rows", entityWaterlist);
        return modelMap;
    }

    /**
     * 数据迁移接口
     * @return
     */
    @RequestMapping(value = "/data_collection", method = RequestMethod.GET)
    @ResponseBody
    public Map<String, Object> dataCollection() throws ParseException {
        //return entityWaterService.dataCollection();
        Map<String, Object> map = new HashMap<>();
        return map;
    }

    @RequestMapping(value = "/selectall_by_companyid_sensor", method = RequestMethod.GET)
    @ResponseBody
    private Map<String, Object> selectAllByCompanyIdSensor(String company_id, String sensor_row_id) throws ParseException {
        Map<String, Object> modelMap = new HashMap<>();
        List<Map<String, Object>> entityWaterlist = entityWaterService.selectEntityWaterByCompanyIdSensor(company_id, sensor_row_id);
        modelMap.put("rows", entityWaterlist);
        return modelMap;
    }

    @RequestMapping(value = "/selectall_by_companyid_sensor__", method = RequestMethod.GET)
    @ResponseBody
    private Map<String, Object> selectAllByCompanyIdSensor__(@RequestParam("limit") int limit,
                                                             @RequestParam("offset") int offset,
                                                             @RequestParam("companyId") String companyId,
                                                             @RequestParam("sensorRowId") String sensorRowId,
                                                             @RequestParam("searchContent") String searchContent) throws ParseException {
        if(searchContent.equals("-")){
            searchContent = "";
        }
        Map<String, Object> modelMap = new HashMap<>();
        List<Map<String, Object>> entityWaterlist = entityWaterService.selectEntityWaterByCompanyIdSensor__(companyId, sensorRowId, offset, limit + offset, searchContent);
        modelMap.put("rows", entityWaterlist);
        modelMap.put("total", entityWaterService.selectEntityWaterSumByCompanyIdSensor(companyId, sensorRowId));
        return modelMap;
    }

    @RequestMapping(value = "/insert", method = RequestMethod.POST)
    @ResponseBody
    public Map<String, Object> insert(@RequestBody EntityWater entityWater) {
        if (entityWater.getCreatedAt() == null) {
            entityWater.setCreatedAt(new Date(System.currentTimeMillis()));
        }

        Map<String, Object> result = new HashMap<>();
        UserEntity user = (UserEntity) session.getAttribute("user");
        Integer operator = user.getId();
        entityWater.setOperator(operator);

        if (entityWater.getOperator() == null) {
            entityWater.setOperator(-1);
        }
        if (entityWater.getLocation() == null) {
            entityWater.setLocation("-");
        }
        return entityWaterService.insertEntityWater(entityWater);
    }

    @RequestMapping(value = "/import", method = RequestMethod.POST)
    @ResponseBody
    public Map<String, Object> importExcel(@RequestParam("file") MultipartFile file,
                                           @RequestParam("companyId") String companyId) {
        boolean insertFlag = true;
        try {
            ArrayList<ArrayList<String>> list = ExcelUtil.analysis(file);
            Map<String, Integer> txtMap= new HashMap<>();
            ArrayList<String> firstList = list.get(0);
            for (int i = 0; i < firstList.size(); i++) {
                txtMap.put(firstList.get(i), i);
            }
            for(int i = 1; i < list.size(); i++) {
                System.out.println(list.get(i));
                EntityWater entity = new EntityWater();
                entity.setSensorRowId(list.get(i).get(txtMap.get("设备编号")));
                entity.setWorkshop(list.get(i).get(txtMap.get("所在位置")));
                entity.setValue(Float.parseFloat(list.get(i).get(txtMap.get("采集数值"))));
                if(txtMap.get("车间名称") != null) {
                    entity.setLocation(list.get(i).get(txtMap.get("车间名称")));
                }
                else {
                    entity.setLocation("-");
                }
                if(txtMap.get("设备类型") != null) {
                    entity.setSensorType(list.get(i).get(txtMap.get("设备类型")));
                }
                else {
                    entity.setSensorType("-");
                }
                if(txtMap.get("最新采集时间") != null) {
                    entity.setCreatedAt(list.get(i).get(txtMap.get("最新采集时间")));
                }
                else {
                    entity.setCreatedAt(new Date().toString());
                }
                if(txtMap.get("录入人员") != null) {
                    entity.setOperator(Integer.parseInt(list.get(i).get(txtMap.get("录入人员"))));
                }
                else {
                    entity.setOperator(0);
                }
                entity.setCompanyId(Integer.parseInt(companyId));
                System.out.println(entity.toString());
                if(!insert(entity).get("status").equals("success")){
                    insertFlag = false;
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        Map<String, Object> temp = new HashMap<>();
        if(insertFlag) {
            temp.put("status", "success");
            temp.put("msg", "插入成功");
        }
        else {
            temp.put("status", "failed");
            temp.put("msg", "插入失败");
        }
        return temp;
    }


    @RequestMapping("/update")
    @ResponseBody
    public Map<String, Object> update(@RequestBody EntityWater entityWater) {
        return entityWaterService.updateEntityWater(entityWater);
    }

    @ResponseBody
    @RequestMapping("/selectEntityWaterByCondition")
    public List<Map<String, Object>> selectEntityWaterByCondition(
            @RequestParam(name = "sensorRowIds") List<String> sensorRowIds,
            @RequestParam(name = "startTime") String startTime, @RequestParam(name = "endTime") String endTime,
            @RequestParam(name = "companyId") String companyId
    ) throws ParseException {
        return entityWaterService.selectEntityWaterByCondition(ListToSqlString.toString(sensorRowIds),startTime,endTime, companyId);
    }

    /**
     查询index页面所需要的数据，即过去一小时、一天、一周、一个月内水信息入库数量
     @ Author Page
     */
    @RequestMapping(value = "/query_index_data", method = RequestMethod.GET)
    @ResponseBody
    private Map<String, Object> queryIndexData() throws ParseException {
        return entityWaterService.queryIndexData();
    }


    /**
     * 查询设备编号对应设备的所有值
     */
    @RequestMapping(value = "/query_value_by_sensor_row_id", method = RequestMethod.GET)
    @ResponseBody
    private Map<String, Object> queryValueBySensorRowId(@RequestParam("businessId") String businessId,@RequestParam("sensorRowId") String sensor_row_id) throws ParseException {
        Map<String, Object> modelMap = new HashMap<>();
        modelMap.put("data", entityWaterService.queryValueBySensorRowId(businessId, sensor_row_id));
        return modelMap;
    }

    /**
     * 查询设备编号对应设备的最新值
     */
    @RequestMapping(value = "/query_new_value_by_sensor_row_id", method = RequestMethod.GET)
    @ResponseBody
    private Map<String, Object> queryNewValueBySensorRowId(@RequestParam("businessId") String businessId,@RequestParam("sensorRowId") String sensor_row_id) throws ParseException {
        Map<String, Object> modelMap = new HashMap<>();
        modelMap.put("data", entityWaterService.queryNewValueBySensorRowId(businessId, sensor_row_id));
        return modelMap;
    }
}
